package com.iflyings.android.util

import java.util.*

object ByteUtils {

    private val HEX_DIGITS = arrayOf(
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'a', 'b', 'c', 'd', 'e', 'f'
    )

    fun toHexString(b: ByteArray): String {
        val sb = StringBuilder(b.size * 2)
        for (i in b.indices) {
            sb.append(HEX_DIGITS[b[i].toInt() and 0xf0 ushr 4])
            sb.append(HEX_DIGITS[b[i].toInt() and 0x0f])
        }
        return sb.toString()
    }

    fun hexStringToByte(str: String): Byte {
        val text = str.lowercase(Locale.getDefault())
        val byteH = HEX_DIGITS.indexOf(text[0])
        val byteL = HEX_DIGITS.indexOf(text[1])
        if (byteH < 0 || byteL < 0) {
            return 0
        }
        return ((byteH shl 4) or byteL).toByte()
    }

}